//
//  WBStatusViewModel.swift
//  SinaWeibo
//
//  Created by zhuangqianwei on 16/11/17.
//  Copyright © 2016年 zhuangqianwei. All rights reserved.
//

import UIKit
import YYText
class WBStatusViewModel: NSObject {

    //增加一个纯种的URL类型的属性--> 记录用户头像地址
    var iconURL: URL?
    
    var verifitedImage: UIImage?
    
    var mbRankImage: UIImage?
    
    var sourceText: String?
    //设置行高 只希望计算一次 以后就直接读取
    var rowHeight: CGFloat = 300

    //原创微博的属性字符串
    var originalAttributedString: NSMutableAttributedString?
    
    //转发微博的属性字符串
    var retweetedAttributedString: NSMutableAttributedString?

    var timeText: String? {
        //1.实例化日期格式化对象
        //2.指定格式化符
        sharedDateFormater.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
        //在真机上必须设置本地化信息否则转换失败
        sharedDateFormater.locale = Locale(identifier: "en")
        //3.将字符串转换日期对象
        guard let sinaDate = sharedDateFormater.date(from: status?.created_at ?? "") else {
            return "骚年"
        }
        //print(sinaDate)
        //4.处理日期
        //4.1 判断是否是今年 Calendar 提供非常丰富的日期处理函数
        let calender = Calendar.current
        let currentDate = Date()
        let result = calender.dateComponents([.day,.year], from: sinaDate, to: currentDate)
        if result.year == 0 {
            //今年
            if calender.isDateInToday(sinaDate) {
                //今天
                //获取当前时间和sinaDate秒的差值
                let delta = currentDate.timeIntervalSince(sinaDate)
                if delta < 60 {
                    //刚刚
                    return "刚刚"
                } else if delta < 3600 {
                    return "\(Int(delta / 60))分钟前"
                } else {
                    return "\(Int(delta / 3600))小时前"
                }
            } else if calender.isDateInYesterday(sinaDate) {
                //昨天 昨天 HH:mm
                sharedDateFormater.dateFormat = "昨天 HH:mm"
                return sharedDateFormater.string(from: sinaDate)
            } else {
                //其他 MM-dd HH:mm
                sharedDateFormater.dateFormat = "MM-dd HH:mm"
                return sharedDateFormater.string(from: sinaDate)
            }
        } else {
            //非当年
            sharedDateFormater.dateFormat = "yyyy-MM-dd HH:mm"
            return sharedDateFormater.string(from: sinaDate)
        }
    }
    //计算型的属性,判断应该返回什么类型微博的pic_urls
    var imageURLs: [WBPictureInfo]? {
        if status?.retweeted_status == nil {
            //原创微博
            return status?.pic_urls
        }
        //转发微博
        return status?.retweeted_status?.pic_urls
    }
    var status: WBStatus? {
        didSet {
            //一旦外界设置值 就应该到didSet中计算用户地址
            iconURL = URL(string: status?.user?.avatar_large ?? "")
            
            //处理微博认证的图片
            self.dealWeiboVerifitedImage()
            self.dealMbrankImage()
            self.sourceText = dealWeiboSource(source: status?.source ?? "")
            self.originalAttributedString =  self.dealWeiboText(str: status?.text ?? "")
            self.retweetedAttributedString = self.dealWeiboText(str: status?.retweeted_status?.text ?? "")

        }
    }

    //将微博正文／转发微博正文处理成附文本
    private func dealWeiboText(str: String) -> NSMutableAttributedString {
        //实力化正则表达式对象 设置查找规则
        let pattern = "\\[.*?\\]"
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        //通过规则在字符串中查找目标字符串 --> ［NStextCheckResult］
        let result = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        //遍历结果集合 获取表情字符串－－  倒序遍历
        
        //将str转换可辨的副文本
        let strM = NSMutableAttributedString(string: str)
        let font = UIFont.systemFont(ofSize: 15)
        let lineHeight = font.lineHeight
        for result in result.reversed() {
            let range = result.rangeAt(0)
            let sub = (str as NSString).substring(with: range)
            //根据表情字符串在表情数组中查找对应的表情模型（图片路径）
            if let em = HMEmoticonTools.sharedEmoticonTools.findEmoticon(chs: sub) {
                print(em)
            //将图片转换为副文本  必须使用YYText提供的副文本的实力化方法
                let image = UIImage(named: em.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)
                let imageText = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFit, attachmentSize: CGSize(width: lineHeight, height: lineHeight), alignTo: font, alignment: .center)
                //将图片副文本替换到str对应的可变的附文本中
                strM.replaceCharacters(in: range, with: imageText)
            }
            
        }
        //给附文本添加字体的属性
        strM.addAttributes([NSFontAttributeName : font], range: NSRange(location: 0, length: strM.length))
        
        addHighlighted(regex: atSomeRegex, strM: strM)
        addHighlighted(regex: topicRegex, strM: strM)
        addHighlighted(regex: urlRegex, strM: strM)
    
        return strM
    }
    //给特殊文本添加高亮
    private func addHighlighted(regex: NSRegularExpression,strM: NSMutableAttributedString) {
        //先给 @某人
        
        let str = strM.string
        //通过规则在字符串中查找目标字符串 －－
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        for result in results {
            let range = result.rangeAt(0)
        //let sub = (str as NSString).substring(with: range)
        //给目标字符串添加颜色
        strM.addAttributes([NSForegroundColorAttributeName : UIColor.orange], range: range)
        
        //给特殊的文本添加点击事件  使用YYText
        let border = YYTextBorder(fill: UIColor.red, cornerRadius: 3)
        let highlight = YYTextHighlight()
        //高亮时文字的颜色
        highlight.setColor(UIColor.blue)
        highlight.setBackgroundBorder(border)
        //2. 把"高亮"属性设置到某个文本范围
        strM.yy_setTextHighlight(highlight, range: range)
    }
    
}
    
    private func dealWeiboSource(source: String) -> String {
        let startFlag = "\">"
        let endFlag = "</a>"
        guard let startRange = source.range(of: startFlag),
            let endRange = source.range(of: endFlag) else {
                return "来自火星"
        }
        
        //upperBound 最大边界 lowerBound: 最小边界
        let range = startRange.upperBound..<endRange.lowerBound
        let subStr = source.substring(with: range)
        return subStr
    }
    
    //处理用户等级图片
    private func dealMbrankImage() {
        let mbrank = status?.user?.mbrank ?? 0
        if mbrank > 0 && mbrank < 7 {
            //赋值
            mbRankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
        
    }
    
    //处理数据相关的业务逻辑 处理微博日期,微博来源
    private func dealWeiboVerifitedImage() {
        //微博认证的图片
        let type = status?.user?.verified_type ?? -1
        //判断type
        switch type {
        case 0:
            verifitedImage = #imageLiteral(resourceName: "avatar_vip")
        case 2,3,5:
            verifitedImage = #imageLiteral(resourceName: "avatar_enterprise_vip")
        case 220:
            verifitedImage = #imageLiteral(resourceName: "avatar_grassroot")
        default:
            //没有认证
            verifitedImage = nil
        }
    }
}
